<?php

class Lockout {

	private $CI;
	private $gc_probability = 5;
	private $info;
	private $insert;
	var $now;
	var $expire;

	/**
	 *  Costructor
	 */
	public function __construct()
	{
		$this->CI =& get_instance();
		$this->now = now();
		$this->expire = $this->now - $this->CI->store->data('setting', 'lockout_expiration');

		$this->_collect_garbage();
	}

	/**
	 * Fetch number of attempts for lockout
	 **/
	function add_attempt($email = '') {

		// We don't need to add a lockout if they've already tried the same email
		if($email) {

			$email = strtolower($email);

			if(!empty($this->info['meta']['email'])) {
				foreach($this->info['meta']['email'] as $e) {
					if(strtolower($e) == $email) {
						return false;
					}
				}
			}
			return false;

			$this->info['meta']['email'][] = $email;

		}

		$this->info['meta']['num']++;
		$tmp_info = $this->info;
		$tmp_info['meta'] = serialize($tmp_info['meta']);

		// Insert the attempt
		if($this->insert) {
			$this->CI->db->insert('user_lockout', $tmp_info);
		} else {
			$this->CI->db->update('user_lockout', $tmp_info);
		}

		return true;

	}

	/**
	 * Fetch number of attempts for lockout
	 **/
	function num_attempts() {

		$ul = $this->CI->db->select('*')->from('user_lockout')
				   ->where(array('time >=' => $this->expire, 'ip' => $this->CI->input->ip_address()))->get();

		// No row, must be new entry
		if(!$ul->num_rows()) {

			$this->insert = true;
			$this->info['ip'] = $this->CI->input->ip_address();
			$this->info['meta'] = array('num' => 0);
			$this->info['time'] = $this->now;

		// Has rows, populate data
		} else {

			$this->insert = false;
			$this->info = $ul->row_array();
			$this->info['meta'] = @unserialize($this->info['meta']);

		}

		return intval($this->info['meta']['num']);

	}

	/**
	 * Delete old sessions when necessary
	 **/
	function _collect_garbage() {

		srand(time());

		if ((rand() % 100) < $this->gc_probability)
		{
			$this->CI->db->where("time < {$this->expire}")->delete('user_lockout');
		}

	}
}